<?php

namespace App\Repositories\Manage;

use App\Models\RoleMenu;
use App\Models\User\Role;

class RoleRepository
{
    public function saveOrUpdate($data = [], $id = 0)
    {
        if (!empty($data['id']))
            unset($data['id']);

        if (!empty($data['s']))
            unset($data['s']);

        if (intval($id)) {
            Role::where("id", $id)->update($data);
            return $id;
        } else {
            $res = Role::create($data);
            return $res['id'] ?? "";
        }
    }

    public function getList($filter = [], $pageNum = 1, $pageSize = 10)
    {
        $res = Role::query()
            ->when(!empty($filter['keywords']), function ($query) use ($filter) {
                return $query->where("name", "like", "%{$filter['keywords']}%");
            })
            ->orderBy("sort", "asc")
            ->orderBy("id", "desc")
            ->paginate($pageSize, "*", null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);

        return $res;
    }

    /**
     * 获取角色对应的菜单
     * @param null $role_id
     */
    public function getMenuIds($role_id = null)
    {
        return RoleMenu::query()->where("role_id", $role_id)->pluck("menu_id")->toArray();
    }

    public function getOne($id = null)
    {
        return Role::query()->where(['id' => $id])->first();
    }

    /**
     * 批量删除
     * @param null $ids
     */
    public function batchDelete($ids = null)
    {
        if (intval($ids)) {
            Role::where(['id' => $ids])->delete();
        } else {
            Role::whereIn("id", $ids)->delete();
        }

        return retSuc([], "删除成功");
    }

    /**
     * 分配菜单权限
     * @param int $role_id
     * @param null $menuIds
     */
    public function assignMenu(int $role_id = 0, $menuIds = null)
    {
        if (!$role_id) return false;
        RoleMenu::query()->where(['role_id' => $role_id])->delete();
        if (empty($menuIds)) return true;

        $data = [];
        foreach ($menuIds as $menuId) {
            $data[] = [
                'role_id' => intval($role_id),
                'menu_id' => intval($menuId)
            ];
        }

        RoleMenu::insert($data);

        return true;
    }

    /**
     * 获取类型
     */
    public function getOptions()
    {
        return Role::query()
            ->where('id', '>', 0)
            ->orderBy("sort", 'asc')
            ->get(['id', 'name', 'code']);
    }

//    检查超级会员数量
    public function getRoleUser($roleCode = null)
    {
        if (empty($roleCode))
            return null;

        $res = Role::from("role")
            ->join("user_role as ur", "ur.role_id", "=", "role.id")
            ->join("user as u", "u.id", "=", "ur.user_id")
            ->whereNull("u.deleted_at")
            ->whereNull("ur.deleted_at")
            ->where("role.code", $roleCode)
            ->get(['role.name', 'u.id', 'u.username']);

        return $res;
    }

}
